# -*- coding: utf-8 -*-
import web,os
from datetime import datetime
from PIL import Image
from PIL.ExifTags import TAGS
import EXIF

 
urls = (
    '/', 'index',
    '/upload_resphoto', 'upload_resphoto',
    '/upload_commcad','upload_commcad',
    '/upload', 'upload',
    '/xls/+', 'xls'
)
 
class index:
    def GET(self):
        todos = db.select('vXls')
        return render.index(todos)
 
class xls:
    def GET(self):
        request = web.input( path=None )
        getPath = request.path
        print getPath
        # if os.path.exists( getPath ):
            # getFile = file( getPath, 'rb' )
            # web.header('Content-type','application/octet-stream')
            # web.header('Content-transfer-encoding','base64') 
            # return base64.standard_b64encode( getFile.read( ) )
        # else:
            # raise web.notfound( )


class upload_commcad:
    def GET(self):
        i = web.input()
        print i
        commid = i.get('commid','0')
        comm=db.select('vCommCad', where="CommID=$commid",vars=dict(commid=int(commid)),_test=False)
        cad=db.select('tCad', where="Community=$commid",vars=dict(commid=int(commid)),_test=False)
        return render.upload_commcad(commid,comm,cad)

    def POST(self):
        x = web.input(myfile = {})
        commid = x.get('commid','0')
        title= x.get('title','')
        memo= x.get('memo','')
        caddir = 'static/cad' # change this to the directory you want to store the file in.
        if 'myfile' in x: # to check if the file-object is created
            filepath = x.myfile.filename.replace('\\','/') # replaces the windows-style slashes with linux ones.
            if title=='':
                cadname = filepath.split('/')[-1].decode('utf-8') # splits the and chooses the last part (the filename with extension)
            else:
                cadname = title
            cadext=filepath.split('.')[-1]
            if cadext.lower() in ('dwg','jpg','doc','docx','xls','xlsx'):
                cadfile=str(commid)+'-'+datetime.strftime(datetime.now(),'%Y%m%d%H%M%S%f')+'.'+cadext
#                photosource = photodir +'/source/'+ photofile

                fout=open(caddir+'/'+cadfile,'wb') # creates the file where the uploaded file should be stored
                fout.write(x.myfile.file.read()) # writes the uploaded file to the newly created file.
                #            fout.write(x.myfile.value) # writes the uploaded file to the newly created file.
                fout.close() # closes the file, upload complete.
    #            im=Image.open(photosource)
    #            im.thumbnail((200,150))
    #            im.save(photodir +'/thumb/'+ photofile)
                uploadtime=datetime.strftime(datetime.now(),'%Y-%m-%d %H:%M:%S')
#                phototime=importtime
#                photomake=''
#                f = open(photosource, 'rb')
#                tags = EXIF.process_file(f)
#                if tags:
#                    try:
#                        phototime=str(tags['EXIF DateTimeOriginal']).replace(':','-',2)
#                        photomake='%s %s'%(tags['Image Make'],tags['Image Model'])
#                    except :
#                        pass
#                photothumb=make_thumb(photosource,sizes=[(200,150)])
    #            db.insert('tResPhoto', ResourceID=resid, PhotoTitle=phototitle, PhotoFile=photosource,PhotoThumb=photothumb, _test=True)
                db.query("insert into tCad (Community,CadName,CadFile,CadRemarks,UploadTime) values (%d,'%s','%s','%s','%s')"%(int(commid),cadname,caddir+'/'+cadfile,memo,uploadtime))
        comm=db.select('vComm', where="CommID=$commid",vars=dict(commid=int(commid)),_test=False)
        cad=db.select('tCad', where="Community=$commid",vars=dict(commid=int(commid)),_test=False)
        return render.upload_commcad(commid,comm,cad)


class upload_resphoto:
    def GET(self):
        i = web.input()
        print i
        resid = i.get('resid','0')
        photo=db.select('tResPhoto', where="ResourceID=$resid",vars=dict(resid=int(resid)),_test=False)
        result=db.select('vRes', where="ResID=$resid",vars=dict(resid=int(resid)),_test=False)
        return render.upload_resphoto(resid,photo,result)

    def POST(self):

        def make_thumb(path, sizes=[(98,80),(150,120)]):
            """
            sizes 参数传递要生成的尺寸，可以生成多种尺寸
            """
            base, ext = os.path.splitext(path)
            try:
                im = Image.open(path)
            except IOError:
                print ' in  IOError'
                return

                # info = im._getexif()
                # ret={}
                # for tag, value in info.items():
                # decoded = TAGS.get(tag, tag)
                # ret[decoded] = value
            # print ret.keys(),ret['DateTimeOriginal']

            mode = im.mode
            if mode not in ('L', 'RGB'):
                if mode == 'RGBA':
                    # 透明图片需要加白色底
                    alpha = im.split()[3]
                    bgmask = alpha.point(lambda x: 255-x)
                    im = im.convert('RGB')
                    # paste(color, box, mask)
                    im.paste((255,255,255), None, bgmask)
                else:
                    im = im.convert('RGB')

            width, height = im.size
            if width == height:
                region = im
            else:
                if width > height:
                    delta = (width - height)/2
                    box = (delta, 0, delta+height, height)
                else:
                    delta = (height - width)/2
                    box = (0, delta, width, delta+width)
            region = im.crop(box)

            for size in sizes:
                filename = base.replace('source','thumb') + "_" + "%sx%s" % (str(size[0]), str(size[1])) + ".jpg"
                thumb = region.resize((size[0],size[1]), Image.ANTIALIAS)
                thumb.save(filename, quality=100) # 默认 JPEG 保存质量是 75, 不太清楚。可选值(0~100)
                return filename


        x = web.input(myfile = {})
        resid = x.get('resid','0')
        title= x.get('title','')
        memo= x.get('memo','')
        photodir = 'static/photo' # change this to the directory you want to store the file in.
        if 'myfile' in x: # to check if the file-object is created
            filepath = x.myfile.filename.replace('\\','/') # replaces the windows-style slashes with linux ones.
            if title=='':
                phototitle = filepath.split('/')[-1].decode('utf-8') # splits the and chooses the last part (the filename with extension)
            else:
                phototitle=title
            photoext=filepath.split('.')[-1]
            if photoext.lower()=='jpg':
                photofile=str(resid)+'-'+datetime.strftime(datetime.now(),'%Y%m%d%H%M%S%f')+'.'+photoext
                photosource = photodir +'/source/'+ photofile
                fout=open(photosource,'wb') # creates the file where the uploaded file should be stored
                fout.write(x.myfile.file.read()) # writes the uploaded file to the newly created file.
                #            fout.write(x.myfile.value) # writes the uploaded file to the newly created file.
                fout.close() # closes the file, upload complete.
                #            im=Image.open(photosource)
                #            im.thumbnail((200,150))
                #            im.save(photodir +'/thumb/'+ photofile)
                importtime=datetime.strftime(datetime.now(),'%Y-%m-%d %H:%M:%S')
                phototime=importtime
                photomake=''
                f = open(photosource, 'rb')
                tags = EXIF.process_file(f)
                if tags:
                    try:
                        phototime=str(tags['EXIF DateTimeOriginal']).replace(':','-',2)
                        photomake='%s %s'%(tags['Image Make'],tags['Image Model'])
                    except :
                        pass
                photothumb=make_thumb(photosource,sizes=[(200,150)])
                #            db.insert('tResPhoto', ResourceID=resid, PhotoTitle=phototitle, PhotoFile=photosource,PhotoThumb=photothumb, _test=True)
                db.query("insert into tResPhoto (ResourceID,PhotoTitle,PhotoFile,PhotoThumb,PhotoTime,ImportTime,PhotoMake,PhotoMemo) values (%d,'%s','%s','%s','%s','%s','%s','%s')"%(int(resid),phototitle,photosource,photothumb,phototime,importtime,photomake,memo))
        photo=db.select('tResPhoto', where="ResourceID=$resid",vars=dict(resid=int(resid)),_test=False)
        result=db.select('vRes', where="ResID=$resid",vars=dict(resid=int(resid)),_test=False)
        return render.upload_resphoto(resid,photo,result)

class upload:
    def POST(self):
        x = web.input(myfile = {})

        filedir = 'upload' # change this to the directory you want to store the file in.
        if 'myfile' in x: # to check if the file-object is created
            filepath = x.myfile.filename.replace('\\','/') # replaces the windows-style slashes with linux ones.
            filename = filepath.split('/')[-1].decode('utf-8') # splits the and chooses the last part (the filename with extension)
            fout = open(filedir +'/'+ filename,'wb') # creates the file where the uploaded file should be stored
            fout.write(x.myfile.file.read()) # writes the uploaded file to the newly created file.
#            fout.write(x.myfile.value) # writes the uploaded file to the newly created file.
            fout.close() # closes the file, upload complete.
        raise web.seeother('/')
 
app = web.application(urls, globals())
render = web.template.render('templates/')
# db = web.database(dbn='sqlite', db=":memory:")
db = web.database(dbn='sqlite', db="res3.db3")
 


if __name__ == "__main__":
    app.run()